﻿using Emgu.CV;
using Emgu.CV.Structure;
using FinalYear.iNavigate.Classes;
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace FinalYear.iNavigate
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Capture capture;
        private MainModel mainModel;
        private DispatcherTimer timer;

        public MainWindow()
        {
            InitializeComponent();
            this.mainModel = new MainModel();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            
            //haarCascade = new HaarCascade(@"haarcascade_frontalface_alt_tree.xml");
            timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = new TimeSpan(0, 0, 0, 0, 1);
            timer.Start();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            mainModel.ProcessFrame();
            //Image<Bgr, Byte> currentFrame = capture.QueryFrame();

            if (mainModel.FlowImage != null)
            {
                //Image<Gray, Byte> grayFrame = currentFrame.Convert<Gray, Byte>();

                //var detectedFaces = grayFrame.DetectHaarCascade(haarCascade)[0];

                //foreach (var face in detectedFaces)
                //    currentFrame.Draw(face.rect, new Bgr(0, double.MaxValue, 0), 3);

                canvas.Background = new ImageBrush(ToBitmapSource(mainModel.FlowImage));
            }
        }

        [DllImport("gdi32")]
        private static extern int DeleteObject(IntPtr o);

        public static BitmapSource ToBitmapSource(IImage image)
        {
            using (Bitmap source = image.Bitmap)
            {
                IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap

                BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    ptr,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

                DeleteObject(ptr); //release the HBitmap
                return bs;
            }
        }
    }
}